package com.kang.controller;

import com.kang.mapper.UsersMapper;
import com.kang.pojo.Items;
import com.kang.pojo.OrderSub;
import com.kang.pojo.Users;
import com.kang.service.AddressService;
import com.kang.service.ItemsService;
import com.kang.service.ShoppingService;
import com.kang.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author 吃三明治派对中的康康
 * @Date 2022/5/1 15:35
 * @Version 1.0
 */
@Controller
public class BuyController {

    @Autowired
    ShoppingService shoppingService;
    @Autowired
    ItemsService itemsService;
    @Autowired
    UsersService usersService;
    @Autowired
    AddressService addressService;

    //购买购物车
    @RequestMapping("/buyShopping")
    String buyShopping(Model model, HttpServletRequest request){

        if(request.getSession().getAttribute("UserSession") == null) return "redirect:/toLogin";

        double pay = 0;
        List<OrderSub> orderSubs = shoppingService.searchAllOrder();
        ArrayList<Items> items = new ArrayList<>();
        //计算总价格
        for (OrderSub orderSub : orderSubs) {
            pay += orderSub.getSum();
            //查找商品信息加入到列表中
            items.add(itemsService.selectGoodsById(orderSub.getId()));
        }
        Users user = (Users) request.getSession().getAttribute("UserSession");

        model.addAttribute("buyModel",items);
        model.addAttribute("buyModelPay",pay);
        model.addAttribute("addressModel",addressService.researchAddressByUid(user.getUid()));

        return "buy";
    }

    //购买单个商品
    @RequestMapping("/buyOne/{goodsId}")
    String buyOne(Model model, @PathVariable int goodsId, HttpServletRequest request){

        if(request.getSession().getAttribute("UserSession") == null){
            return "redirect:/toLogin";
        }
        Users user = (Users) request.getSession().getAttribute("UserSession");
        model.addAttribute("oneGoods",itemsService.selectGoodsById(goodsId));
        model.addAttribute("addressModel",addressService.researchAddressByUid(user.getUid()));
        return "buy";
    }


}
